import {computed, reactive, watch} from 'vue'
import {selectCartByUserId, insertShopCart, updateCartItemNum, deleteCartItem, clearCarts} from '@/router/api'
import {useUserStore} from "@/stores/userStore.js";

const userStore = useUserStore();
const userId = computed(() => userStore.userInfo?.id)
const cartStore = reactive([])

// 获取购物车数据
const fetchCart = async () => {
    if (!userId.value) return
    try {
        const res = await selectCartByUserId(userId.value)
        cartStore.splice(0, cartStore.length, ...res)
    } catch (error) {
        console.error('获取购物车失败:', error)
    }
}

// 监听用户ID变化
watch(userId, (newVal) => {
        if (newVal) {
            fetchCart().then()
        }
    },
    {immediate: true}
)
export const useCartStore = () => {

    // 添加商品
    const addToCart = async (product, quantity) => {
        if (!userId.value) throw new Error('请先登录')
        try {
            await insertShopCart({
                userid: userId.value,
                goodid: product.id,
                num: quantity
            })
            await fetchCart() // 刷新数据
        } catch (error) {
            console.error('添加失败:', error)
            throw error
        }
    }

    // 修改数量
    const updateQuantity = async (gooditemid, num) => {
        try {
            await updateCartItemNum(gooditemid, num)
            await fetchCart()
        } catch (error) {
            console.error('更新失败:', error)
            throw error
        }
    }

    // 删除商品
    const removeItem = async (gooditemid) => {
        try {
            await deleteCartItem(userId.value, gooditemid)
            await fetchCart()
        } catch (error) {
            console.error('删除失败:', error)
            throw error
        }
    }

    // 清空购物车
    const clearCart = async () => {
        try {
            await clearCarts(userId.value)
            cartStore.splice(0, cartStore.length)
        } catch (error) {
            console.error('清空失败:', error)
            throw error
        }
    }

    // 计算总价
    const getTotalPrice = computed(() => {
        return cartStore.reduce((sum, item) => {
            return sum + (item.sale_price * item.num)
        }, 0)
    })

    return {
        cartStore,
        getTotalPrice,
        fetchCart,
        addToCart,
        removeItem,
        clearCart,
        updateQuantity,
    }
}